<script setup lang="ts">
import { ContentWrap } from '@/components/ContentWrap'
import { Search } from '@/components/Search'
import { Dialog } from '@/components/Dialog'
import { useI18n } from '@/hooks/web/useI18n'
import { ElButton, ElMessage } from 'element-plus'
import { Table } from '@/components/Table'
import { repertoryIndex, storeAdd, storeEdit, storeDel, goodsSelect } from '@/api/common'
import { useTable } from '@/hooks/web/useTable'
import { storageType } from '@/api/common/types'
import { ref, unref, reactive, h } from 'vue'
import { useRouter } from 'vue-router'
const { push } = useRouter()
// import Write from './components/addWrite.vue'
import Detail from './components/Detail.vue'
import { CrudSchema, useCrudSchemas } from '@/hooks/web/useCrudSchemas'
// import AppView from '@/layout/components/AppView.vue'
import { useAppStoreWithOut } from '@/store/modules/app'
import { useCache } from '@/hooks/web/useCache'
const appStore = useAppStoreWithOut()
const { wsCache } = useCache()
//用户权限数组
const userRlues = wsCache.get(appStore.getUserInfo).rlues
const userId = wsCache.get(appStore.getUserInfo).id

const checkRlues = (rlues) => {
  //检查权限
  if (userRlues.includes(rlues)) {
    return true
  } else {
    ElMessage.error('当前用户无权限操作，请联系管理员')
    return false
  }
}
const { register, tableObject, methods } = useTable<storageType>({
  getListApi: repertoryIndex,
  delListApi: storeDel,
  response: {
    list: 'data',
    total: 'total'
  },
  defaultParams: {
    title: ''
  },
  find: ''
})

const { getList, setSearchParams } = methods

getList()
const { t } = useI18n()

const crudSchemas = reactive<CrudSchema[]>([
  {
    field: 'index',
    label: t('tableDemo.index'),
    type: 'index',
    form: {
      show: false
    },
    detail: {
      show: false
    }
  },
  {
    field: 'gname',
    label: '货品名称',
    search: {
      show: true
    },
    form: {
      colProps: {
        span: 24
      }
    },
    detail: {
      span: 24
    }
  },
  {
    field: 'store_text',
    label: '所在仓库',
    search: {
      show: true
    },
    form: {
      show: false,
      colProps: {
        span: 24
      }
    },
    detail: {
      span: 24
    }
  },

  {
    field: 'goods_text',
    label: '货品类型',
    search: {
      show: true,
      component: 'Select',
      api: async () => {
        const res: any = await goodsSelect({})
        let list: any = []
        res.data.list.forEach((item) => {
          list.push({
            label: item.name,
            value: item.id
          })
        })
        localStorage.setItem('goodsSelectData', JSON.stringify(list))
        return list
      },
      componentProps: {
        filterable: true,
        options: []
      }
    },
    table: {},
    form: {
      colProps: {
        span: 24
      }
    },
    detail: {
      span: 24
    }
  },
  {
    field: 'client_code',
    label: '客户号',
    search: {
      show: true
    },
    form: {
      colProps: {
        span: 24
      }
    },
    detail: {
      span: 24
    }
  },
  {
    field: 'shouhuo',
    label: '收货人',
    search: {
      show: false
    },
    form: {
      colProps: {
        span: 24
      }
    },
    detail: {
      span: 24
    }
  },
  {
    field: 'destinations',
    label: '目的地',
    search: {
      show: false
    },
    form: {
      colProps: {
        span: 24
      }
    },
    detail: {
      span: 24
    }
  },
  {
    field: 'piece',
    label: '件数',
    search: {
      show: false
    },
    form: {
      colProps: {
        span: 24
      }
    },
    detail: {
      span: 24
    }
  },
  {
    field: 'quantity',
    label: '每件数量',
    search: {
      show: false
    },
    form: {
      colProps: {
        span: 24
      }
    },
    detail: {
      span: 24
    }
  },
  {
    field: 'total',
    label: '库存总数量',
    search: {
      show: false
    },
    form: {
      colProps: {
        span: 24
      }
    },
    detail: {
      span: 24
    }
  },
  {
    field: 'weight',
    label: '重量',
    search: {
      show: false
    },
    form: {
      colProps: {
        span: 24
      }
    },
    detail: {
      span: 24
    }
  },
  {
    field: 'volume',
    label: '体积',
    formatter: (row) => {
      return h(
        'span',
        row.length && row.width && row.high
          ? (Number(row.length) * Number(row.width) * Number(row.high)).toFixed(2)
          : 0
      )
    },
    search: {
      show: false
    },
    form: {
      colProps: {
        span: 24
      }
    },
    detail: {
      span: 24
    }
  },
  {
    field: 'remark',
    label: '备注',
    search: {
      show: false
    },
    form: {
      colProps: {
        span: 24
      }
    },
    detail: {
      span: 24
    }
  },
  {
    field: 'action',
    width: '260px',
    label: t('tableDemo.action'),
    form: {
      show: false
    },
    fixed: 'right',
    detail: {
      show: false
    }
  }
])

const { allSchemas } = useCrudSchemas(crudSchemas)

const dialogVisible = ref(false)

const dialogTitle = ref('')

const AddAction = (row, rlues) => {
  if (checkRlues(rlues)) push('/warehouseManagement/warehouseGoodsEdit?id=' + row.id)
}
// const delLoading = ref(false)

// const delData = async (row: storageType | null, multiple: boolean) => {
//   tableObject.currentRow = row
//   const { delList, getSelections } = methods
//   const selections = await getSelections()
//   delLoading.value = true
//   await delList(
//     multiple ? selections.map((v) => v.id) : [tableObject.currentRow?.id as string],
//     multiple
//   ).finally(() => {
//     delLoading.value = false
//   })
// }

const actionType = ref('')

const action = (row: storageType, type: string, rlus: string) => {
  if (!checkRlues(rlus)) return false
  dialogTitle.value = t(type === 'edit' ? 'exampleDemo.edit' : 'exampleDemo.detail')
  actionType.value = type
  tableObject.currentRow = row
  dialogVisible.value = true
}

const writeRef = ref<ComponentRef<typeof Write>>()

const loading = ref(false)

const addSave = async () => {
  const write = unref(writeRef)
  await write?.elFormRef?.validate(async (isValid) => {
    if (isValid) {
      loading.value = true
      const data = (await write?.getFormData()) as storageType
      const res = await storeAdd(data)
        .catch(() => {})
        .finally(() => {
          loading.value = false
        })
      if (res) {
        dialogVisible.value = false
        tableObject.currentPage = 1
        getList()
      }
    }
  })
}
const save = async () => {
  const write = unref(writeRef)
  await write?.elFormRef?.validate(async (isValid) => {
    if (isValid) {
      loading.value = true
      const data = (await write?.getFormData()) as storageType
      const res = await storeEdit(data, data.id)
        .catch(() => {})
        .finally(() => {
          loading.value = false
        })
      if (res) {
        dialogVisible.value = false
        tableObject.currentPage = 1
        getList()
      }
    }
  })
}
</script>

<template>
  <ContentWrap>
    <Search :model="{ title: '' }" :schema="allSchemas.searchSchema" @reset="setSearchParams" />

    <div class="mb-10px">
      <!-- <ElButton :loading="delLoading" type="danger" @click="delData(null, true)">
        {{ t('exampleDemo.del') }}
      </ElButton> -->
    </div>

    <Table
      v-model:pageSize="tableObject.limit"
      v-model:currentPage="tableObject.currentPage"
      :columns="allSchemas.tableColumns"
      :data="tableObject.tableList"
      :loading="tableObject.loading"
      :pagination="{
        total: tableObject.total
      }"
      @register="register"
    >
      <template #action="{ row }">
        <!-- <ElButton type="primary" @click="action(row, 'edit')">
          {{ t('exampleDemo.edit') }}
        </ElButton> -->
        <ElButton type="primary" @click="AddAction(row, '29-2')">{{
          t('exampleDemo.edit')
        }}</ElButton>

        <ElButton type="success" @click="action(row, 'detail', '29-5')">
          {{ t('router.watch') }}
        </ElButton>
        <!-- <ElButton type="danger" @click="delData(row, false)">
          {{ t('exampleDemo.del') }}
        </ElButton> -->
      </template>
    </Table>
  </ContentWrap>

  <Dialog v-model="dialogVisible" :title="dialogTitle">
    <Write
      v-if="actionType !== 'detail'"
      ref="writeRef"
      :form-schema="allSchemas.formSchema"
      :current-row="tableObject.currentRow"
    />

    <Detail
      v-if="actionType === 'detail'"
      :detail-schema="allSchemas.detailSchema"
      :current-row="tableObject.currentRow"
    />

    <template #footer>
      <ElButton
        v-if="actionType !== 'detail' && actionType !== 'edit'"
        type="primary"
        :loading="loading"
        @click="addSave"
      >
        {{ t('exampleDemo.save') }}
      </ElButton>
      <ElButton v-if="actionType == 'edit'" type="primary" :loading="loading" @click="save">
        {{ t('exampleDemo.save') }}
      </ElButton>
      <ElButton @click="dialogVisible = false">{{ t('dialogDemo.close') }}</ElButton>
    </template>
  </Dialog>
</template>
